package com.cdream.basic.algorithm.leetcode.linkedlist;

import java.util.LinkedList;

/**
 * 一套操作猛入虎，一看击败5%
 * @author cdream
 * @date 6/13/21
 */
public class Question25 {
    public static void main(String[] args) {
        ListNode node1 = new ListNode(1);
        ListNode node2 = new ListNode(2);
        node1.next = node2;
        System.out.println(new Question25().reverseKGroup(node1, 2));

    }

    public ListNode reverseKGroup(ListNode head, int k) {
        LinkedList<ListNode> listNodes = new LinkedList<>();
        ListNode dummy = new ListNode(-1);
        dummy.next = head;
        ListNode cur = head;
        ListNode pre = dummy;
        while (cur != null || listNodes.size()==k) {
            if (listNodes.size() != k) {
                listNodes.push(cur);
                cur = cur.next;
            } else {
                while (listNodes.size() != 0) {
                    ListNode pop = listNodes.pop();
                    pop.next = null;
                    pre.next = pop;
                    pre = pre.next;
                }
                pre.next = cur;
            }

        }
        return dummy.next;
    }
}
